package com.tim.helper.analysis;

import com.tim.ArgConstant;
import com.tim.helper.CountRuntime;
import com.tim.util.CmdAndShUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 数据库表结构导出插件
 *  https://gitee.com/leshalv/screw
 *  show databases  查看全部数据库
 *  select VERSION()  查看数据库版本，修改pom依赖版本

 <configuration>
     <!-- 数据库连接信息 -->
     <driverClassName>com.mysql.cj.jdbc.Driver</driverClassName>
     <url>jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC</url>
     <username>your_username</username>
     <password>your_password</password>

     <!-- 文档生成设置 -->
     <outputDir>${project.build.directory}</outputDir>
     <fileName>database_doc.html</fileName>
     <title>Database Documentation</title>
     <description>Generated by Screw</description>

     <!-- 可选：指定要包含或排除的表 -->
     <includeTables>
         <param>table1</param>
         <param>table2</param>
     </includeTables>
     <excludeTables>
        <param>table_to_exclude</param>
     </excludeTables>

     <!-- 是否打开生成后的文件 -->
     <openOutputFile>true</openOutputFile>
 </configuration>
 */
public class SrewPluginHelper extends CountRuntime {
    // 中台 店绩
    String project = "中台";
    // 数据库信息；before方法中按project设置
    String username,password,dbname,ipPortDb;
    String excludeTableInfo ="";

    // 以下一般不改
    String projectDir = System.getProperty("user.dir");
    StringBuilder tableNameBuilder = new StringBuilder("DB:\n  TABLE: TABLE_NAME；表描述\n");

    @Before
    public void init() throws Exception {
        // 中台 店绩
        if("中台".equals(project)){
            userPlatformDb();
        }else{
            throw new RuntimeException("project 参数不正确");
        }

    }

    @Test
    public void multiDb() throws Exception {
        List<String> projects = Arrays.asList(""
                .split(","));
        String excludeDbs = "information_schema,mysql,test,sys,__recycle_bin__,performance_schema," +
                "test1";
            List<String> excludeDbList = Arrays.asList(excludeDbs.split(","));
        projects = projects.stream()
                    .filter(e->!excludeDbList.contains(e))
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());

        for(String item : projects){
            project = item;
            init();
            ipPortDb = ipPortDb.substring(0, ipPortDb.indexOf("/"))+"/"+item;
            singleDb();
            // 移动到对应文件夹
//            File destDir = Paths.get(projectDir, "doc", project).toFile();
//            if(!destDir.exists()){
//                destDir.mkdirs();
//            }
//            Files.move(Paths.get(projectDir, "doc", dbname+".html"),
//                    Paths.get(projectDir, "doc", project, dbname+".html"),
//                    StandardCopyOption.REPLACE_EXISTING);
        }
    }

    @Test
    public void singleDb() throws Exception {

        String jdbcUrl = String.format("jdbc:mysql://%s?useSSL=false", ipPortDb);
//        String driverClassName = "com.mysql.jdbc.Driver";// mysql 5
        String driverClassName = "com.mysql.cj.jdbc.Driver";// mysql 8
        tableNameBuilder.append(dbname+": \n");

        /* step1，修改pom插件配置，运行插件*/
        String pomPath = projectDir+"/pom.xml";
        MavenXpp3Reader POM_READER = new MavenXpp3Reader();
        Model pomModel = POM_READER.read(new FileReader(pomPath));
        List<Plugin> plugins = pomModel.getBuild().getPlugins();
        boolean returnFlag = true;
        for(Plugin plugin : plugins){
            if(plugin.getArtifactId().equals("screw-maven-plugin")){
                returnFlag = false;
                Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
                configuration.getChild("jdbcUrl").setValue(jdbcUrl);
                configuration.getChild("username").setValue(username);
                configuration.getChild("password").setValue(password);
                configuration.getChild("driverClassName").setValue(driverClassName);
                configuration.getChild("fileName").setValue(dbname);
                configuration.getChild("openOutputDir").setValue("true");
                configuration.getChild("title").setValue(dbname +"文档");
                configuration.getChild("description").setValue(dbname +"文档生成");
                Xpp3Dom ignoreTableNameNode = configuration.getChild("ignoreTableName");
                if(ignoreTableNameNode==null){
                    ignoreTableNameNode=new Xpp3Dom("ignoreTableName");
                    configuration.addChild(ignoreTableNameNode);
                }
                for (int i = 0; i < ignoreTableNameNode.getChildCount(); i++) {
                    ignoreTableNameNode.removeChild(i);
                }
                String[] excludeTables = excludeTableInfo.replaceAll("\\s","").split(",");
                for (int i = 0; StringUtils.isNotBlank(excludeTableInfo)&&i < excludeTables.length; i++) {
                    Xpp3Dom param = new Xpp3Dom("param");
                    param.setValue(excludeTables[i]);
                    ignoreTableNameNode.addChild(param);
                }
                break;
            }
        }
        if(returnFlag){
            return;
        }
        MavenXpp3Writer POM_WRITER = new MavenXpp3Writer();
        POM_WRITER.write(new FileWriter(pomPath), pomModel);

        // 运行插件，获取命令
        String cmd = System.getProperty("user.dir").replace(":", ": && cd ")+" && mvn screw:run";
        CmdAndShUtil.runBat(cmd);
    }




    private void userPlatformDb(){
        username = "root";
        password = "shpDb@2022";
        dbname = project;
        ipPortDb = "162.14.204.178:13336/"+dbname;
    }

    @After
    public void after() throws Exception {

    }

    @Test
    public void printTableHref(){
        // 中台 店绩
        String dic = "中台";
        String destDir = ArgConstant.PROJECT_PATH+"doc/"+dic;
        String[] list = new File(destDir).list();
        String lineTemplate = "<li><a href=\"./%1$s/%2$s.html\" target=\"_blank\">%2$s</a></li>";
        Arrays.stream(list)
                .filter(StringUtils::isNotBlank)
                .forEach(
                        e -> {
                            System.out.println(String.format(lineTemplate, dic, e.substring(0, e.length()-5)));
                        });
    }
}
